from playwright.sync_api import sync_playwright
import time
import random

port = 'wb'
user = r'13283766953'
passwd = r'Ws123456+++'


def on_response(response):
    # print(f'statue {response.status}:{response.url}:{response}')
    if r'https://cpquery.cponline.cnipa.gov.cn/connect/user' in response.url:
        print(response)


def on_request(request):
    # 监听请求信息，发现登录请求，识别出authorization
    if r'https://cpquery.cponline.cnipa.gov.cn/connect/user' in request.url:
        headers = request.headers
        authorization = headers.get('authorization')
        print('@@成功获取authorization信息:%s' % authorization)
        with open('%s_author.txt' % port, 'w', encoding='utf-8') as file:
            file.write(authorization)


def login_get_authorization(user, passwd):
    # 使用账号密码登录，获取账号的授权信息
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto('https://cpquery.cponline.cnipa.gov.cn/chinesepatent/index')
        page.wait_for_load_state('networkidle')
        page.click('xpath=//span[text()="自然人登录"]')
        time.sleep(1)
        page.click('xpath=//input[@placeholder="手机号/证件号码"]')
        time.sleep(0.5)
        page.fill('xpath=//input[@placeholder="手机号/证件号码"]', user)
        time.sleep(1)
        page.click('xpath=//input[@placeholder="请输入密码"]')
        time.sleep(0.5)
        page.fill('xpath=//input[@placeholder="请输入密码"]', passwd)
        time.sleep(0.5)
        page.click('xpath=//span[text()="登录"]')
        input('滑动验证登录网站：')
        page.on('request', on_request)
        page.reload()
        page.wait_for_load_state('networkidle')
        # page.on('requestfinished', on_request)
        page.remove_listener('request', on_request)
        # browser.close()
        # 定时刷新页面登录信息保活
        while True:
            time.sleep(random.randint(10, 20))
            page.reload()


if __name__ == '__main__':
    login_get_authorization(user, passwd)
